package com.keldian.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.keldian.mobilesafe.R;
import com.keldian.mobilesafe.utils.SharePrefenceTool;
import com.keldian.mobilesafe.utils.StreamTools;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SlashActivity extends Activity {

    protected static final String TAG = "SplashActivity";
    protected static final int SHOW_UPDATE_DIALOG = 0;
    protected static final int ENTER_HOME = 1;
    protected static final int URL_ERROR = 2;
    protected static final int NETWORK_ERROR = 3;
    protected static final int JSON_ERROR = 4;
    private TextView tv_splash_version;
    private String description;
    private TextView tv_update_info;
    /**
     * 新版本的下载地址
     */
    private String apkurl;
    private int versionCode;
    //版本名称
    private String version;

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slash);


        tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
        tv_splash_version.setText("版本号" + getVersionName());
        tv_update_info = (TextView) findViewById(R.id.tv_update_info);

//        copyDB("address.db");
        copyDB("antivirus.db");

        checkUpdate();


        AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);
        aa.setDuration(1500);

        findViewById(R.id.rl_root_splash).startAnimation(aa);

        //checkupdate
        installShortCut();

    }

    private void installShortCut() {
        sp = getSharedPreferences("mobilesafe", Context.MODE_PRIVATE);
        if (sp.getBoolean("shortcut", false)) {
            return;
        }
        SharedPreferences.Editor editor = sp.edit();
        Intent intent = new Intent();
        intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "My MobileSafe");
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
        Intent shortcutIntent = new Intent();
        shortcutIntent.setAction("android.intent.action.MAIN");
        shortcutIntent.addCategory("android.intent.category.LAUNCHER");
        shortcutIntent.setClassName(getPackageName(), "com.keldian.mobilesafe.activity.SlashActivity");
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        sendBroadcast(intent);
        editor.putBoolean("shortcut", true);
        editor.commit();

    }

    private void copyDB() {
//        try {
////            File file = new File(getFilesDir(), "address.db");
////            if (file.exists() && file.length() > 0) {
////                Log.i(TAG, "normal");
////            } else {
////                InputStream is = getAssets().open("address.db");
////                FileOutputStream fos = new FileOutputStream(file);
////                byte[] buffer = new byte[1024];
////                int len = 0;
////                while ((len = is.read(buffer)) != -1) {
////                    fos.write(buffer, 0, len);
////                }
////                is.close();
////                fos.close();
////            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    private void copyDB(String filename) {
        try {
            File file = new File(getFilesDir(), filename);
            if (file.exists() && file.length() > 0) {
                Log.i(TAG, "normal");
            } else {
                InputStream is = getAssets().open(filename);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_UPDATE_DIALOG:// 显示升级的对话框
                    Log.i(TAG, "显示升级的对话框");
                    showUpdateDialog();
                    break;
                case ENTER_HOME:// 进入主页面
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            enterHome();
                        }
                    }, 2000);
                    break;
                case URL_ERROR:// URL错误
                    enterHome();
                    Toast.makeText(getApplicationContext(), "URL错误", Toast.LENGTH_SHORT).show();

                    break;

                case NETWORK_ERROR:// 网络异常
                    enterHome();
                    Toast.makeText(SlashActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                    break;

                case JSON_ERROR:// JSON解析出错
                    enterHome();
                    Toast.makeText(SlashActivity.this, "JSON解析出错", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }


    };

    /**
     * Show Update UI
     */
    private void showUpdateDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(SlashActivity.this);
        builder.setTitle("XXX");
        builder.setCancelable(false);
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                enterHome();
                dialog.dismiss();
            }
        });

        builder.setMessage(description);

        builder.setPositiveButton("update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    FinalHttp finalHttp = new FinalHttp();
                    finalHttp.download("http://file.liqucn.com/upload/pojie/shenmiaotaowang2.apk", Environment.getExternalStorageDirectory()
                            .getAbsolutePath() + "/mobileSafe.apk", new AjaxCallBack<File>() {
                        @Override
                        public void onLoading(long count, long current) {
                            super.onLoading(count, current);
                            tv_update_info.setVisibility(View.VISIBLE);
                            int progress = (int) (current * 100 / count);
//                            Log.i(TAG,(current / count)+"");
//                            Log.i(TAG,count+"");
                            tv_update_info.setText("下载进度：" + progress + "%");
                        }

                        @Override
                        public void onSuccess(File file) {
                            super.onSuccess(file);
                            installAPK(file);
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            t.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "下载失败", Toast.LENGTH_LONG).show();
                            super.onFailure(t, errorNo, strMsg);

                        }
                    });
                } else {
                    Toast.makeText(getApplicationContext(), "没有sdcard，请安装上在试",
                            Toast.LENGTH_LONG).show();
                    return;
                }
            }
        });
        builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(SlashActivity.this, "您可以在主页设置中进行设置",
                        Toast.LENGTH_LONG).show();
                dialog.dismiss();
                enterHome();// 进入主页面
            }
        });
        builder.setNeutralButton("忽略这个版本", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(SlashActivity.this, "您可以在主页设置中进行设置",
                        Toast.LENGTH_LONG).show();
                SharePrefenceTool.setUpdateVersion(SlashActivity.this, version);
                dialog.dismiss();
                enterHome();// 进入主页面
            }
        });
        builder.show();
    }

    /**
     * Install download apk
     *
     * @param file
     */
    private void installAPK(File file) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }


    /**
     * Enter HomePage UI
     */
    private void enterHome() {
        Intent intent = new Intent(SlashActivity.this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * Check update or not检查是否需要升级
     */
    private void checkUpdate() {
        new Thread() {
            public void run() {
                //URL http://192.168.0.166:8080/mobileSafe/updateinfo.html
                final Message mes = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    URL url = new URL(getString(R.string.serverurl));
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(4000);
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        String result = StreamTools.readFromStream(is);
                        Log.i(TAG, "OK!" + result);
                        JSONObject obj = new JSONObject(result);

                        version = (String) obj.get("version");

                        description = (String) obj.get("description");
                        apkurl = (String) obj.get("apkurl");
                        Log.i(TAG, !SharePrefenceTool.getSharePreferences(SlashActivity.this) + "");
                        Log.i(TAG, SharePrefenceTool.getUpdateVersion(SlashActivity.this)
                                .equals(version) + "---" + SharePrefenceTool.getUpdateVersion(SlashActivity.this));

                        if (!SharePrefenceTool.getSharePreferences(SlashActivity.this) && (
                                SharePrefenceTool.getUpdateVersion(SlashActivity.this)
                                        .equals(version))) {
                            mes.what = ENTER_HOME;
                        } else {
                            mes.what = SHOW_UPDATE_DIALOG;
                        }
                    }
                } catch (MalformedURLException e) {
                    mes.what = URL_ERROR;
                    e.printStackTrace();
                } catch (IOException e) {
                    mes.what = NETWORK_ERROR;
                    e.printStackTrace();
                } catch (JSONException e) {
                    mes.what = JSON_ERROR;
                    e.printStackTrace();
                } finally {
                    long endTime = System.currentTimeMillis();
                    if ((endTime - startTime) < 2000) {
                        try {
                            Thread.sleep(2000 - (endTime - startTime));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    handler.sendMessage(mes);
                }

            }
        }.start();
    }

    /**
     * Get the VersionName 得到版本名称
     *
     * @return
     */
    private String getVersionName() {
        // 用来管理手机的APK
        PackageManager pm = getPackageManager();

        try {
            // 得到知道APK的功能清单文件
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

    }

    //获取版本编号VersionCode
    private int getVersionCode() {
        // 用来管理手机的APK
        PackageManager pm = getPackageManager();

        try {
            // 得到知道APK的功能清单文件
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }

    }

}
